<?php

namespace App\Http\Controllers\Users;
use App\Blocks\User;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Wechat\ServerController;
use App\Models\AgentApply;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class UserController extends Controller {

    public function weixinCallback(Request $request){
        $app = Factory::officialAccount(\Config::get('wechat'));
        $oauth = $app->oauth;
        $user = $oauth->user();

        $userBlock = new User();
        $userInfo = $userBlock->getUserByWxOpenid($user->getId());
        if(!$userInfo){
            $wxuser = $user->getOriginal();
            \Log::debug(json_encode($wxuser));
            global $wechatId;

            $saveUserData = [
                'wechat_id'         => $wechatId,
                'subscribe_time'    => isset($wxuser['subscribe_time'])?date('Y-m-d H:i:s', $wxuser['subscribe_time']):null,
                'openid'            => $wxuser['openid'],
                'nickname'          => isset($wxuser['nickname'])?$wxuser['nickname']:null,
                'city'              => isset($wxuser['city'])?$wxuser['city']:null,
                'province'          => isset($wxuser['province'])?$wxuser['province']:null,
                'country'           => isset($wxuser['country'])?$wxuser['country']:null,
                'sex'               => isset($wxuser['sex'])?$wxuser['sex']:null,
                'headimgurl'        => isset($wxuser['headimgurl'])?$wxuser['headimgurl']:null,
                'subscribe'         => isset($wxuser['subscribe'])?$wxuser['subscribe']:0,
                'create_time'       => date('Y-m-d H:i:s', time()),
                'father_id'         => 0,
                'is_agent'          => 0,
            ];
            $userId = $userBlock->saveUserByWeixin($saveUserData);

            if($userId){
                $userInfo = [
                    'openid' => $saveUserData['openid'],
                    'wx_openid' => $saveUserData['wx_openid'],
                    'headimgurl' => $saveUserData['headimgurl'],
                    'nick_name' => $saveUserData['nickname'],
                    'mobile' => null,
                    'id' => $userId,
                    'father_id'         => 0,
                    'is_agent'          => 0,
                ];

                $userInfo = (object)$userInfo;
            }
        }

        if(isset($userInfo->id)){
            if(isset($userInfo->create_time)){
                unset($userInfo->create_time);
            }

            //绑定代理逻辑----start-----
            //只有没有绑定过上级代理的用户才能继续绑定上级
            try{
                if($request->has('agent') && (!isset($userInfo->father_id) || $userInfo->father_id == 0)){
                    $agentId = $request->get('agent');
                    $agentInfo = \App\Models\User::where('id', $agentId)->where('is_agent', 1)->first();
                    if(!$agentInfo){
                        \Log::error("上级代理ID没有找到；上级ID:{$agentId},用户ID:{$userInfo->id}");
                    }else{
                        if(
                            \App\Models\User::where('id', $userInfo->id)
                                ->where('father_id', 0)
                                ->update([
                                    'father_id' => $agentId,
                                ]) === false
                        ){
                            \Log::waring("更新father_id失败；上级ID:{$agentId},用户ID:{$userInfo->id}");
                        }else{
                            $wechatServerController = new ServerController();
                            global $appId;
                            \Log::debug($appId);
                            $tempid = 'T5aGjrCD9MUZRGgk09lQuzcIqEeH-01JSj4ONJ52tzY';
                            $tempData = [
                                'first' => "恭喜您有新的下级加入",
                                'keyword1' => $userInfo->id,
                                'keyword2' => date('Y-m-d H:i:s', time()),
                                'keyword3' => $userInfo->nick_name
                            ];
                            $tempUrl = env('APP_URL')."/api/wechat/login?appid={$appId}&redirect=center";
                            $wechatServerController->sendTempMsg($appId, $agentInfo->wx_openid,$tempid,$tempData,$tempUrl);
                        }
                    }
                }
            }catch (\Exception $exception){
                \Log::error($exception);
                \Log::error("绑定失败,用户ID:{$userInfo->id}");
            }
            //绑定代理逻辑----end-----

            $sessionKey = md5($userInfo->wx_openid);
            \Cache::put($sessionKey, $userInfo, \Config::get('session.lifetime'));
            $cookie = \Cookie::make(\Config::get('session.taoke_user_cookie'), $sessionKey, \Config::get('session.lifetime'));

            $userInfo->token = $sessionKey;

            if($request->has('redirect')){
                $redirect = $request->get('redirect');
                $url = env('WEB_URL').'/taoke';
                if($redirect === 'index'){
                    $url = env('WEB_URL').'/taoke';
                }elseif($redirect === 'goodsshare'){
                    //跳转商品详情页面
                    $tbid = $request->get('goodsid');
                    $url = env('WEB_URL')."/goods/info/{$tbid}/wechatimg";
                }elseif($redirect === 'center'){
                    //跳转个人中心页面
                    if($userInfo->is_agent == 0){
                        $apply = AgentApply::where('uid', $userInfo->id)->orderBy('created_at', 'desc')->first();
                        if(!$apply){
                            $url = env('WEB_URL').'/Login';
                        }else{
                            $url = env('WEB_URL')."/Examine?status={$apply->status}&remark={$apply->remark}";
                        }
                    }else{
                        $url = env('WEB_URL').'/User';
                    }
                }elseif($request->get('redirect') == 'yizhandaodi'){
                    return redirect("http://boshi.wedoyun.com/wechat/oauth_callback?openid={$userInfo->wx_openid}");
                }

                $url .= "?token={$userInfo->token}";
                return redirect($url)->withCookie($cookie);
            }
            return response()->json($userInfo)->withCookie($cookie);
        }else{
            return response()->json(['error' => '登录失败']);
        }
    }
}